package com.example.weight.greenSeasons.flocculation;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.compost.CompostMonthMaintenanceActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class xuningyuebaoyang extends AppCompatActivity {
    private String name, role, fName ,factory;

    private TextView content1, content2, content3, content4;
            //c1Check, c2Check, c3Check, c4Check;

    private RadioGroup rg1, rg2, rg3, rg4;

    private RadioButton rb1Normal, rb1Abnormal, rb2Normal, rb2Abnormal, rb3Normal, rb3Abnormal
            , rb4Normal, rb4Abnormal;



    private LinearLayout optionalCheckBox, optionalText;

    private Map<String, String> fromIdMap;

    private RequestQueue queue;

    private List<TextView> names;
    List<RadioGroup> radioGroups = new ArrayList<>();

    private List<RadioButton> normalButtons;
    private List<RadioButton> abnormalButtons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuningyuebaoyang);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        fName = previousIntent.getStringExtra("fName");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.xuningMonth_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                if (rg1.getCheckedRadioButtonId() == -1) {
                    allDone(content1.getText().toString());
                }else if (rg2.getCheckedRadioButtonId() == -1) {
                    allDone(content2.getText().toString());
                }else if (rg3.getCheckedRadioButtonId() == -1) {
                    allDone(content3.getText().toString());
                }else if (rg4.getCheckedRadioButtonId() == -1) {
                    allDone(content4.getText().toString());
                }else {
                    xuningyuebaoyang.this.finish();
                }
            }
            @Override
            public void onTitleClick(View v) {}
            @Override
            public void onRightClick(View v) {}
        });

        TextView actualDate = findViewById(R.id.xuningMonth_date);
        String tempText = actualDate.getText().toString();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        actualDate.setText(tempText+year+"-"+month+"-"+day);

        // 保养内容
        content1 = findViewById(R.id.xuningMonth_content1);
        content2 = findViewById(R.id.xuningMonth_content2);
        content3 = findViewById(R.id.xuningMonth_content3);
        content4 = findViewById(R.id.xuningMonth_content4);

        names = new ArrayList<>();
        names.add(content1);   names.add(content2);   names.add(content3);   names.add(content4);

        rg1 = findViewById(R.id.rg1);
        rg2 = findViewById(R.id.rg2);
        rg3 = findViewById(R.id.rg3);
        rg4 = findViewById(R.id.rg4);

        //Radio Button Normal
        rb1Normal = findViewById(R.id.rb1_normal);
        rb2Normal = findViewById(R.id.rb2_normal);
        rb3Normal = findViewById(R.id.rb3_normal);
        rb4Normal = findViewById(R.id.rb4_normal);

        //Radio Button Abnormal
        rb1Abnormal = findViewById(R.id.rb1_abnormal);
        rb2Abnormal = findViewById(R.id.rb2_abnormal);
        rb3Abnormal = findViewById(R.id.rb3_abnormal);
        rb4Abnormal = findViewById(R.id.rb4_abnormal);

        optionalCheckBox = findViewById(R.id.xuningMonth_optional_checkBox);
//        optionalText = findViewById(R.id.xuningMonth_optional_text);

        fromIdMap = new HashMap<>();

        queue = Volley.newRequestQueue(this);

        normalButtons = new ArrayList<>();
        normalButtons.add(rb1Normal);  normalButtons.add(rb2Normal);
        normalButtons.add(rb3Normal);  normalButtons.add(rb4Normal);
        abnormalButtons = new ArrayList<>();
        abnormalButtons.add(rb1Abnormal); abnormalButtons.add(rb2Abnormal);
        abnormalButtons.add(rb3Abnormal); abnormalButtons.add(rb4Abnormal);

        radioGroups.add(rg1);   radioGroups.add(rg2);
        radioGroups.add(rg3);   radioGroups.add(rg4);

        // 根据不同系统名称，设置不同保养内容
        switch (fName) {
            case "喂料泵1":
            case "喂料泵2":
                initialCheckStatus();
                break;
            case "1#絮凝脱水系统":
            case "2#絮凝脱水系统":
            case "3#絮凝脱水系统":
                content1.setText("检查控制系统");
                content2.setText("除锈喷漆");
                content3.setText("酸洗栅网");
                content4.setText("更换毛刷");
                initialCheckStatus();
                break;
            case "除臭系统":
                optionalCheckBox.setVisibility(View.GONE);
                content1.setText("清洗滤尘网，检查气密");
                content2.setText("轴承加油，叶轮做动平衡");
                content3.setText("更换轴承");
                initialCheckStatus();
                break;
        }

        for (int i = 0; i < names.size(); i++) {
            String eqName = names.get(i).getText().toString();
            RadioButton normal = normalButtons.get(i), abnormal = abnormalButtons.get(i);
            RadioGroup group = radioGroups.get(i);
            normal.setOnClickListener(v -> {
                if (normal.isChecked()) {
                    saveNormal(eqName, normal, abnormal, group);
                }
            });
            abnormal.setOnClickListener(v -> {
                if (abnormal.isChecked()) {
                    saveAbnormal(eqName, normal, abnormal, group);
                }
            });
        }

        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/sjqCompostProduceMaintenance/getMonthRecords";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("zjyMonthTest", response);
                            JSONObject jsonObject = new JSONObject(response);
                            if(!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if(data.length() > 0){
                                    for(int i = 0; i < data.length(); i++){
                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                        JSONObject record = data.getJSONObject(i);
                                        // 得到 每个对象中的属性值
                                        for (int j = 0; j < names.size(); j++) {
                                            String maintainContent = names.get(j).getText().toString();
                                            RadioButton normal = normalButtons.get(j);
                                            RadioButton abnormal = abnormalButtons.get(j);
                                            if (record.getString("maintenanceContent")
                                                    .equals(maintainContent)) {
                                                if(record.get("isNormal").equals("正常")){
                                                    normal.setChecked(true);
                                                }else {
                                                    abnormal.setChecked(true);
                                                }
                                                if(!record.isNull("operator")){
                                                    normal.setClickable(false);
                                                    abnormal.setClickable(false);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuningyuebaoyang.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipment_name", fName);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        Log.d("zjyEquipmentName: ", fName);

//        //equip_1
//        rb1Normal.setOnClickListener(v -> {
//            if (rb1Normal.isChecked()) {
//                saveNormal(content1.getText().toString(), rb1Abnormal, rb1Normal,rg1);
//            }
//        });
//        rb1Abnormal.setOnClickListener(v -> {
//            if (rb1Abnormal.isChecked()) {
//                saveAbnormal(content1.getText().toString(), rb1Abnormal, rb1Normal,rg1);
//            }
//        });
//        //equip_2
//        rb2Normal.setOnClickListener(v -> {
//            if (rb2Normal.isChecked()) {
//                saveNormal(content2.getText().toString(), rb2Abnormal, rb2Normal,rg2);
//            }
//        });
//        rb2Abnormal.setOnClickListener(v -> {
//            if (rb2Abnormal.isChecked()) {
//                saveAbnormal(content2.getText().toString(), rb2Abnormal, rb2Normal,rg2);
//            }
//        });
//        //equip_3
//        rb3Normal.setOnClickListener(v -> {
//            if (rb3Normal.isChecked()) {
//                saveNormal(content3.getText().toString(), rb3Abnormal, rb3Normal,rg3);
//            }
//        });
//        rb3Abnormal.setOnClickListener(v -> {
//            if (rb3Abnormal.isChecked()) {
//                saveAbnormal(content3.getText().toString(), rb3Abnormal, rb3Normal,rg3);
//            }
//        });
//        //equip_4
//        rb4Normal.setOnClickListener(v -> {
//            if (rb4Normal.isChecked()) {
//                saveNormal(content4.getText().toString(), rb4Abnormal, rb4Normal,rg4);
//            }
//        });
//        rb4Abnormal.setOnClickListener(v -> {
//            if (rb4Abnormal.isChecked()) {
//                saveAbnormal(content4.getText().toString(), rb4Abnormal, rb4Normal,rg4);
//            }
//        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        Intent intent = new Intent();
        intent.putExtra("needRefresh", true);
        setResult(RESULT_OK, intent);
    }

    private void setCheckStatus(TextView operatorCB, RadioGroup radioGroup) throws UnsupportedEncodingException {
        String operatorCBText = operatorCB.getText().toString();
        String[] temp = operatorCBText.split("[ \n]");
        String equipment_name = URLEncoder.encode(fName, "utf-8");
        String maintainContent = URLEncoder.encode(temp[0], "utf-8");
        String url = Config.url + "/sjq/flocculationProduceMaintenanceMonth/getMonthRecords";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.d("setCheckStatus",response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
//                                operatorCB.setChecked(true);
                                operatorCB.setEnabled(false);
                                operatorCB.setTextColor(Color.GREEN);
//                                setRemarks(operatorCB, data.getString("remarks"));

                                String examiner = data.getString("examiner");
                                if (!examiner.equals("") && !examiner.equals("null")) {
                                    // 检查人已检查某项，该项不可再检查
//                                    radioGroup.setChecked(true);
//                                    examinerCB.setEnabled(false);
//                                    examinerCB.setTextColor(Color.GREEN);
                                    enableRadioGroup(radioGroup);
                                } else {
                                    // 若存在检查人未检查项，将其添加到formIdList中
                                    fromIdMap.put(temp[0], data.getString("id"));
                                }
//                                if (role.equals("检查人")) {
//
//                                }
                            } else {
                                if (role.equals("检查人")) {
                                    // 如果操作人未保养，检查人不可检查
                                    operatorCB.setEnabled(false);
//                                    examinerCB.setEnabled(false);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuningyuebaoyang.this,
                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipment_name", fName);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }


    public void saveNormal(String maintainContent, RadioButton normal_rb, RadioButton abnormal_rb, RadioGroup rb) {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("确定 “"+ maintainContent +"” 正常？")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    rb.clearCheck();
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/flocculationProduceMaintenanceMonth/add_recorder";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Toast.makeText(xuningyuebaoyang.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else {
                                            Toast.makeText(xuningyuebaoyang.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                            normal_rb.setChecked(false);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(xuningyuebaoyang.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", fName);
                            map.put("maintenance_content", maintainContent);
                            map.put("is_normal","正常");
                            map.put("remarks", "-1");
                            map.put("operator", name);
                            map.put("factory", factory);
//                            Log.d("zjyMap", map.toString());
//                            Log.d("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void saveAbnormal(String maintainContent, RadioButton normal_rb, RadioButton abnormal_rb, RadioGroup rb) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new AlertDialog.Builder(this)
                .setTitle("请填写 “"+ maintainContent +"” 异常原因？")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    rb.clearCheck();
                }
                ))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/flocculationProduceMaintenanceMonth/add_recorder";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            normal_rb.setClickable(false);
                                            abnormal_rb.setClickable(false);
                                            Toast.makeText(xuningyuebaoyang.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else {
                                            Toast.makeText(xuningyuebaoyang.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                            abnormal_rb.setChecked(false);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(xuningyuebaoyang.this,
                                    "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name", fName);
                            map.put("maintenance_content", maintainContent);
                            map.put("is_normal","异常");
                            map.put("remarks", equipment_problem.getText().toString());
                            map.put("operator", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void allDone(String equipment_name){
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle(" “"+ equipment_name +"” 未检查，是否退出")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) -> {
                    return;
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    xuningyuebaoyang.this.finish();
                })
                .show();
    }

    private void initialCheckStatus() {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/flocculationProduceMaintenanceMonth/getMonthRecords";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("zys", response);
                            JSONObject jsonObject = new JSONObject(response);
                            if(!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if(data.length() > 0){
                                    for(int i = 0; i < data.length(); i++){
                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                        JSONObject record = data.getJSONObject(i);
                                        // 得到 每个对象中的属性值
                                        for (int j = 0; j < names.size(); j++) {
                                            String maintainContent = names.get(j).getText().toString();
                                            RadioButton normal = normalButtons.get(j);
                                            RadioButton abnormal = abnormalButtons.get(j);
                                            if (record.getString("maintenanceContent")
                                                    .equals(maintainContent)) {
                                                if(record.get("isNormal").equals("正常")){
                                                    normal.setChecked(true);
                                                }else {
                                                    abnormal.setChecked(true);
                                                }
                                                if(!record.isNull("operator")){
                                                    normal.setClickable(false);
                                                    abnormal.setClickable(false);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuningyuebaoyang.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map=new HashMap<>();
                map.put("equipment_name", fName);
                map.put("factory", factory);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    public void disableRadioGroup(RadioGroup testRadioGroup) {
        for (int i = 0; i < testRadioGroup.getChildCount(); i++) {
            testRadioGroup.getChildAt(i).setEnabled(false);
        }
    }

    public void enableRadioGroup(RadioGroup testRadioGroup) {
        for (int i = 0; i < testRadioGroup.getChildCount(); i++) {
            testRadioGroup.getChildAt(i).setEnabled(true);
        }
    }
}